package me.shurufa.activities;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.widget.SlidingPaneLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

import java.io.File;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.adapter.MenuListAdapter;
import me.shurufa.controller.CheckUpdateController;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.fragments.DiscoveryFragment;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.CheckVersionResp;
import me.shurufa.response.GetNoticeNumResp;
import me.shurufa.response.StatResp;
import me.shurufa.service.BackgroundService;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;
import me.shurufa.widget.crop.util.FileUtils;
import me.shurufa.widget.smoothcamera.core.CameraManager;

public class NewMainActivity extends AppCompatActivity implements View.OnClickListener, SlidingPaneLayout.PanelSlideListener {

    @Bind(R.id.ll_menu)
    LinearLayout mMenuLayout;
    @Bind(R.id.slidepanel)
    SlidingPaneLayout mSlidingPaneLayout;
    @Bind(R.id.menuRv)
    RecyclerView mMenuRv;
    @Bind(R.id.back)
    ImageView mMenuIv;

    @Bind(R.id.right_image)
    ImageView mUserAvatarIv;
    @Bind(R.id.search_edit)
    TextView mSearchEt;  // 搜索
    @Bind(R.id.ll_search_bar)
    LinearLayout ll_search_bar;

    @Bind(R.id.iv_notice_num)
    ImageView iv_notice_num;

    private SparseArray<Fragment> fragments = new SparseArray<>(6);
    private CheckUpdateController mCheckController;
    private MenuListAdapter mMenuAdapter; // 左侧菜单适配器

    private Handler mHandler = new Handler();
    private int mNewSelectedMenuIndex;
    private int mSelectedMenuIndex = 0; // 选中的菜单索引 默认是第0个

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                        | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        //| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                //window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                //window.setNavigationBarColor(Color.TRANSPARENT);
            } else {
                //透明状态栏
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                //透明导航栏
                //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
        }
        setContentView(R.layout.activity_new_main);
        setStatusBar();
        init();
        initViews();
        switchFragment(mSelectedMenuIndex, true); // 默认第0页

        //delayLoadStat();
        delayCheckUpdate();
        startGrayDaemonService();
    }

    private void startGrayDaemonService() {
        Intent bgIntent = new Intent(this, BackgroundService.class);
        startService(bgIntent);
    }

    /**
     * 切换Fragment
     *
     * @param index 索引
     * @param force 是否重新new
     */
    public void switchFragment(int index, boolean force) {

        if (!PersistenceUtils.isLogin()) {
            if (index == 3 || index == 4 || index == 5) {
                Utils.showToast(getString(R.string.login_id));
                Intent in = new Intent(this, NewLoginActivity.class);
                in.setAction(Constants.ACTION_GO_LOGIN);
                EventBus.getDefault().postSticky(in);
                return;
            }
        }

        if (mSelectedMenuIndex == index && !force) {
            return;
        }
        Fragment oldFragment = fragments.get(mSelectedMenuIndex);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        if (oldFragment != null)
            ft.hide(oldFragment);

        mSelectedMenuIndex = index;
        // 不加判断每次切换tab都刷新   code by andy
        Fragment newFragment = null;
        switch (mSelectedMenuIndex) {
            case 0: // 最新上架
                newFragment = DiscoveryFragment.newInstance(Constants.TYPE_FRAGMENT_NEWEST_BOOK);
                break;
            case 1: // 最多书评
                newFragment = DiscoveryFragment.newInstance(Constants.TYPE_FRAGMENT_MOST_COMMENT);
                break;
            case 2: // 最多书摘
                newFragment = DiscoveryFragment.newInstance(Constants.TYPE_FRAGMENT_MOST_EXCERPT);
                break;
            /*case 2: // 编辑推荐
                newFragment = new BookRecommendFragment();
                break;*/
            case 3: // 我的书架  切记看本类最后一个方法 还有个切换到我的书架刷新
                newFragment = DiscoveryFragment.newInstance(Constants.TYPE_FRAGMENT_MYSHELF);
                break;
            case 4: // 我的收藏
                newFragment = DiscoveryFragment.newInstance(Constants.TYPE_FRAGMENT_MYCOLLECT);
                break;
            case 5: // 我的评论
                newFragment = DiscoveryFragment.newInstance(Constants.TYPE_FRAGMENT_MYCOMMENT);
                break;
            default:
                newFragment = DiscoveryFragment.newInstance(Constants.TYPE_FRAGMENT_NEWEST_BOOK);
        }

        fragments.put(mSelectedMenuIndex, newFragment);
        if (newFragment != null) {
            if (!newFragment.isAdded()) {
                ft.add(R.id.fl_content, newFragment, String.valueOf(mSelectedMenuIndex));
            }
            ft.show(newFragment);
        }
        ft.commitAllowingStateLoss();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (PersistenceUtils.isLogin()) {
            reqGetUnreadMessage();
        } else {
            iv_notice_num.setVisibility(View.GONE);
        }

        if (mUserAvatarIv != null) {
            if (!TextUtils.isEmpty(PersistenceUtils.getAvatar())) {
                Glide.with(this).load(PersistenceUtils.getAvatar() + Constants.THUMB_SUFFIX_AVATAR).asBitmap().centerCrop().into(new BitmapImageViewTarget(mUserAvatarIv) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                        circularBitmapDrawable.setCircular(true);
                        mUserAvatarIv.setImageDrawable(circularBitmapDrawable);
                    }
                });
            } else {
                mUserAvatarIv.setImageResource(R.drawable.ic_def_avatar);
            }
        }
    }

    private void initViews() {

        // 左侧菜单列表
        String[] stringArray = this.getResources().getStringArray(R.array.menu_list);
        List<String> menuList = Arrays.asList(stringArray);
        mMenuAdapter = new MenuListAdapter(this, menuList, mSelectedMenuIndex);
        mMenuRv.setAdapter(mMenuAdapter);
        mMenuRv.setLayoutManager(new LinearLayoutManager(this));
        mMenuRv.setOverScrollMode(View.OVER_SCROLL_NEVER);

        // SlidingPaneLayout
        mSlidingPaneLayout.setSliderFadeColor(Color.TRANSPARENT);
        mSlidingPaneLayout.setPanelSlideListener(this);
        mMenuIv.setOnClickListener(this);
        mUserAvatarIv.setOnClickListener(this);

        ll_search_bar.setOnClickListener(this);
        mSearchEt.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {

                    // 校验空
                    String book_title = mSearchEt.getText().toString();
                    if (TextUtils.isEmpty(book_title)) {
                        return false;
                    }

                    // 触发-进搜索界面
                    Intent in = new Intent(NewMainActivity.this, MainSearchBookActivity.class);
                    in.putExtra(Constants.ARG_BOOK_TITLE, book_title);
                    startActivity(in);

                    // 防止-焦点下移
                    return true;
                }

                return false;
            }
        });
    }

    private void init() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        // 配置在线策略 检查更新
        // MobclickAgent.updateOnlineConfig(this);
        // UmengUpdateAgent.update(this);
        //异常退出后所有内存中的全局变量会被销毁 所以再次判断
        // if (Global.currentUser == null)
        //    Global.appInit(this);
        checkWritePermission();
    }

    /**
     * 检查写入权限
     */
    private void checkWritePermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (checkCameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.READ_PHONE_STATE}, Constants.REQUEST_WRITE);
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                handleSlidingPaneLayout();
                break;
            case R.id.right_image:
                handleClickAvatar();
                break;
            case R.id.ll_search_bar:
                // 触发-进搜索界面
                Intent in = new Intent(NewMainActivity.this, MainSearchBookActivity.class);
                startActivity(in);
                break;
        }

    }


    /**
     * 处理点击图标
     * 1. 未登录 跳转至登录界面
     * 2. 已登录 进入到个人信息界面
     */
    private void handleClickAvatar() {
        Intent in;
        // 已登录 跳转到ProfileActivity
        if (PersistenceUtils.isLogin()) {
            in = new Intent(this, ProfileActivity.class);
            startActivity(in);
        }

        // 未登录 则跳转至登录界面，点击登录时需要返回到当前界面
        else {
            in = new Intent(this, NewLoginActivity.class);
            in.setAction(Constants.ACTION_GO_LOGIN);
            EventBus.getDefault().postSticky(in);
            startActivity(in);
        }
    }

    /**
     * 跳转到新加书摘本界面
     */
    private void startAddDigestAct() {
        Intent in = new Intent(this, NewDigestBookActivity.class);
        startActivity(in);
    }

    /**
     * 处理左滑菜单状态
     */
    private void handleSlidingPaneLayout() {
        if (mSlidingPaneLayout.isOpen()) {
            mSlidingPaneLayout.closePane();
        } else {
            mSlidingPaneLayout.openPane();
        }
    }

    /**
     * 去相机界面
     */
    private void goCamera() {
        CameraManager.getInstance().openCamera(this);
    }

    private void checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constants.REQUEST_CAMERA);
                return;
            } else {
                goCamera();
            }
        } else {
            goCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case Constants.REQUEST_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    goCamera();
                } else {
                    Utils.showToast(R.string.permission_decline);
                }
                break;
            case Constants.REQUEST_WRITE:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Utils.showToast(R.string.permission_decline);
                    finish();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    //    double click
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
        }
        return false;
    }

    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit;
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, getString(R.string.double_click_back), Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            finish();
        }
    }


    // 退出应用时 删除照相和上传头像的临时文件
    @Override
    protected void onDestroy() {
        File mTempDir = new File(Environment.getExternalStorageDirectory(), "shurufa_temp");
        if (mTempDir.exists()) {
            FileUtils.deleteFile(mTempDir);
        }

        if (mCheckController != null) {
            mCheckController.release();
        }

        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPanelSlide(View panel, float slideOffset) {

        mMenuLayout.setScaleY(1.1F - slideOffset / 10);
        mMenuLayout.setScaleX(1.1F - slideOffset / 10);
        // mMenuLayout.setAlpha(slideOffset / 2 + 0.5F);

        // 键盘缩回
        collaspingSoftInput();
    }

    @Override
    public void onPanelOpened(View panel) {
        mMenuAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPanelClosed(View panel) {
        // 切换Fragment
        switchFragment(mNewSelectedMenuIndex, false);
    }

    /**
     * 点击左侧不同菜单Item 切换不同Fragment
     *
     * @param in action
     */
    public void onEventMainThread(Intent in) {
        // 匹配
        if (Constants.ACTION_CHANGE_MENU.equals(in.getAction())) {
            int currIndex = in.getIntExtra(Constants.EXTRA_SWITCH_INDEX, 0);
            mNewSelectedMenuIndex = currIndex;
            mMenuAdapter.notifyDataSetChanged();
            // 关闭菜单
            handleSlidingPaneLayout();
        }

        // 显示头像
        if (Constants.EVENT_SHOW_USER_AVATAR.equals(in.getAction())) {
            Glide.with(this).load(PersistenceUtils.getAvatar() + Constants.THUMB_SUFFIX_AVATAR).asBitmap().centerCrop().into(new BitmapImageViewTarget(mUserAvatarIv) {
                @Override
                protected void setResource(Bitmap resource) {
                    super.setResource(resource);
                    RoundedBitmapDrawable circularBitmapDrawable =
                            RoundedBitmapDrawableFactory.create(NewMainActivity.this.getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    mUserAvatarIv.setImageDrawable(circularBitmapDrawable);
                }
            });
        }

        // 添加书摘
        if (Constants.EVENT_MAIN_MENU_ADD_DIGEST.equals(in.getAction())) {
            if (PersistenceUtils.isLogin()) {
                checkCameraPermission();
            }
        }

        // 添加书摘本
        if (Constants.EVENT_MAIN_MENU_ADD_NOTEBOOK.equals(in.getAction())) {
            if (PersistenceUtils.isLogin()) {
                startAddDigestAct();
            }
        }

    }

    public void onEventMainThread(String action) {
        // 添加完书摘本跳到主页 需要切换到我的书架并刷新
        if (Constants.EVENT_SWITCH_MY_SHELF.equals(action)) {
            switchFragment(3, true);
            mSelectedMenuIndex = 3;
            mNewSelectedMenuIndex = 3;
            mMenuAdapter.notifySelectedIndex(3);
        }
    }


    /**
     * 收缩键盘
     */
    private void collaspingSoftInput() {
        switch (mNewSelectedMenuIndex) {
            case 3:

                DiscoveryFragment shelf = (DiscoveryFragment) fragments.get(mNewSelectedMenuIndex);
                if (null != shelf) {
                    shelf.resetSearchBar();
                }

                break;
            case 4:

                DiscoveryFragment favorite = (DiscoveryFragment) fragments.get(mNewSelectedMenuIndex);
                if (null != favorite) {
                    favorite.resetSearchBar();
                }

                break;
            case 5:

                DiscoveryFragment comment = (DiscoveryFragment) fragments.get(mNewSelectedMenuIndex);
                if (null != comment) {
                    comment.resetSearchBar();
                }

                break;
        }
    }


    /**
     * 请求未读消息
     */
    private void reqGetUnreadMessage() {

        RequestParams params = new RequestParams();
        HttpRequest.post(API.GET_NOTICE_NUM, params, new HttpCallback<GetNoticeNumResp>() {
            @Override
            public void onRespSuccess(GetNoticeNumResp resp) {
                try {
                    int unreadTotal = Integer.valueOf(resp.data.total_num);
                    iv_notice_num.setVisibility(unreadTotal > 0 ? View.VISIBLE : View.GONE);
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(GetNoticeNumResp resp) {

            }
        });

    }

    /**
     * 延迟500毫秒请求更新
     */
    private void delayLoadStat() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                reqStatSettings();
            }
        }, 300);
    }

    /**
     * 延迟500毫秒请求更新
     */
    private void delayCheckUpdate() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                checkUpdate();
            }
        }, 500);
    }

    /**
     * 请求初始化数据
     */
    private void reqStatSettings() {
        RequestParams params = new RequestParams();
        HttpRequest.post(API.STAT, params, new HttpCallback<StatResp>() {
            @Override
            public void onRespSuccess(StatResp statResp) {
                try {
                    int searchType = statResp.data.local_search;
                    if (searchType != PersistenceUtils.getSearchType()) {
                        PersistenceUtils.setSearchType(searchType);
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(StatResp statResp) {

            }

        });
    }

    /**
     * 检测是否有更新
     */
    private void checkUpdate() {

        RequestParams params = new RequestParams();
        HttpRequest.post(API.CHECK_UPDATE, params, new HttpCallback<CheckVersionResp>() {
            @Override
            public void onRespSuccess(CheckVersionResp resp) {
                try {
                    // 校验是否需要强制更新
                    CheckVersionResp.Version data = resp.data;
                    if (data == null) {
                        return;
                    }

                    mCheckController = new CheckUpdateController(NewMainActivity.this);
                    // 提示强制更新
                    if (data.mustUpdate == 1) {
                        mCheckController.forceUpdate(data.downloadUrl, data.newVersion, data.whatsNew);
                        return;
                    }

                    // 提示需要更新
                    if (data.needUpdate == 1) {
                        mCheckController.needUpdate(data.downloadUrl, data.newVersion, data.whatsNew);
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(CheckVersionResp checkVersionResp) {

            }
        });

    }

    /**
     * 设置沉浸式状态栏
     */
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final ViewGroup container = (ViewGroup) findViewById(R.id.container);
            final int statusHeight = getStatusBarHeight();
            container.setPadding(0, statusHeight, 0, 0);
        }
    }

    /**
     * 获取状态栏的高度
     *
     * @return height
     */
    protected int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}
